import OpenAI from 'openai'

export async function chat(prompt: string, problem: string) {
  try {
    const config = localStorage.getItem('openapiConfig')
    if (config) {
      const apiConfig = JSON.parse(config)
      const openai = new OpenAI({
        apiKey: apiConfig.apiKey,
        baseURL: apiConfig.baseUrl,
        dangerouslyAllowBrowser: true,
      })
      const completion = await openai.chat.completions.create({
        messages: [
          { role: 'system', content: prompt },
          { role: 'user', content: problem },
        ],
        model: apiConfig.modelName,
      })
      return completion.choices[0]?.message?.content
    }
    else {
      return null
    }
  }
  finally { /* empty */ }
}
